package com.iraeta.common;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;

@ControllerAdvice
public class GlobalException {
    private static final Logger logger = LoggerFactory.getLogger(GlobalException.class);

    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public String handleServiceException(ServiceException e) {
        logger.error(e.getMessage());
        return JSON.toJSONString(Result.error(e.getCode(), e.getMessage())) ;
    }

    @ExceptionHandler(SQLException.class)
    @ResponseBody
    public String handleException(SQLException e) {
        return JSON.toJSONString(Result.error("500", "数据库异常")) ;
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handleException(Exception e) {
        return JSON.toJSONString(Result.error("500", e.getMessage())) ;
    }
}
